package com.example.workapp;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;


public class TransferFilesActivity extends AppCompatActivity {
// Android 11 及以上版本使用 Scoped Storage 策略，传统的外部存储权限 (READ_EXTERNAL_STORAGE)
// 无法直接访问文件路径。因此，使用 Storage Access Framework (SAF) 是推荐的做法。
    private static final int REQUEST_CODE_SELECT_FILE = 1;
    private Button btnSelectFile;
    private Button btnTransfer;
    private Uri selectedFileUri;
    private Button btnAcceptFile;
    private Button btnBlueAcceptFile;
    private int flag = 0;
//    private String mimeType;

    private static final String bluetoothAddress = "B4:A5:AC:D6:E4:4C";  // 示例蓝牙地址
    private static final String TARGET_DEVICE_MAC_ADDRESS = "36:ea:8c:81:9e:c9";  // mac地址

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_files);

        btnSelectFile = findViewById(R.id.btnSelectFile);
        btnTransfer = findViewById(R.id.btnTransfer);
        btnAcceptFile = findViewById(R.id.btnAcceptFile);
        btnBlueAcceptFile = findViewById(R.id.btnwifiAcceptFile);

        // 设置按钮默认为不可用状态
        btnTransfer.setEnabled(false);

        btnSelectFile.setOnClickListener(v -> openFileChooser());
        btnTransfer.setOnClickListener(v -> transferFile());
        btnAcceptFile.setOnClickListener(v -> acceptFile());
        btnBlueAcceptFile.setOnClickListener(v -> acceptwifiFile());
    }

    // 打开文件选择器
    private void openFileChooser() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);//saf获取文件url
        intent.setType("*/*"); // 可以选择所有文件类型
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    private void acceptFile(){
        Intent intent = new Intent(this,BluetoothClientActivity.class);
        startActivity(intent);
    }

    private void acceptwifiFile(){
        Intent intent = new Intent(this,WifiClientActivity.class);
        intent.putExtra("flag",flag);
        startActivity(intent);
    }

    // 处理文件选择结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT_FILE && resultCode == RESULT_OK && data != null) {
            selectedFileUri = data.getData();
//            DocumentFile documentFile = DocumentFile.fromSingleUri(this, selectedFileUri);
//            if (documentFile != null) {
//                String mimeType;
//                mimeType = documentFile.getType();
//                System.out.println("文件MIME类型: " + mimeType);
//            }
            if (selectedFileUri != null) {
                System.out.println("选择文件成功");
                btnTransfer.setEnabled(true);  // 启用传输按钮
            } else {
                Log.d("TransferFilesActivity", "selectedFileUri is null");
            }
        }
    }

    // 传输文件
    public void transferFile() {
        if (selectedFileUri != null) {
            long fileSize = getFileSize(selectedFileUri);
            if (fileSize > 0) {
                // Choose the transfer method based on file size
//                if (fileSize < 1024 * 1024) { // For example, if file size is less than 1MB
                if (fileSize < 1024 * 1024) { // 例如，文件大小小于 1MB
                    showTransferConfirmationDialog("蓝牙", () -> startBluetoothTransferActivity());
                } else {
                    showTransferConfirmationDialog("WiFi", () -> startWiFiDirectTransferActivity());
                }
            } else {
                Toast.makeText(this, "Unable to determine file size.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "No file selected.", Toast.LENGTH_SHORT).show();
        }
    }

    private void showTransferConfirmationDialog(String transferType, Runnable onConfirm) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("准备传输文件")
                .setMessage("请在另一台设备上点击“接受" + transferType + "文件”。")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 用户点击确定后执行回调
                    onConfirm.run();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // 用户点击取消，关闭弹窗
                    dialog.dismiss();
                })
                .setCancelable(false) // 禁止点击弹窗外关闭
                .show();
    }

    private long getFileSize(Uri fileUri) {
        long fileSize = -1;
        // 获取ContentResolver
        try (Cursor cursor = getContentResolver().query(fileUri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                if (sizeIndex != -1) {
                    fileSize = cursor.getLong(sizeIndex);  // 获取文件大小（字节）
                    Log.d("FileSize", "File size: " + fileSize + " bytes");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSize;
    }

    private void startBluetoothTransferActivity() {
        // Start Bluetooth transfer activity
        System.out.println("进入蓝牙");
        Intent intent = new Intent(this, BluetoothActivity.class);
        intent.putExtra("FILE_PATH", selectedFileUri);
        intent.putExtra("bluetoothAddress",bluetoothAddress);
//        intent.putExtra("mimeType",mimeType);
        System.out.println(selectedFileUri);
        System.out.println(bluetoothAddress);
        startActivity(intent);
    }

    private void startWiFiDirectTransferActivity() {
        // Start Wi-Fi Direct transfer activity
        System.out.println("进入wifi-direct");
        Intent intent = new Intent(this, WiFiActivity.class);
        intent.putExtra("flag",flag);
        intent.putExtra("FILE_PATH", selectedFileUri);
        intent.putExtra("TARGET_DEVICE_MAC_ADDRESS", TARGET_DEVICE_MAC_ADDRESS);
        startActivity(intent);

    }


//    // 获取文件的实际路径（通过 URI）
//    private String getRealPathFromURI(Uri contentUri) {
//        String filePath = null;
//
//        // 如果 URI 是 content://，则尝试从 ContentResolver 获取文件路径
//        if ("content".equals(contentUri.getScheme())) {
//            // 使用 try-with-resources 确保 InputStream 自动关闭
//            try (InputStream inputStream = getContentResolver().openInputStream(contentUri)) {
//                if (inputStream != null) {
//                    // 尝试获取文件的路径
//                    filePath = contentUri.getPath();
//                    Log.d("getRealPath", "File path: " + filePath);
//                }
//            } catch (IOException e) {
//                // 捕获并打印异常
//                e.printStackTrace();
//                Log.e("getRealPath", "Error opening input stream", e);
//            }
//        }
//
//        return filePath;
//    }


//    // 使用 SAF 打开文件进行处理
//    private void openDocument(Uri uri) {
//        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        startActivity(intent);
//    }
}
